/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.uhk.ppro.traveler.logic;

import cz.uhk.ppro.traveler.dao.UsersDao;
import cz.uhk.ppro.traveler.entity.TUser;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author dusi
 */
public class RegisterActionBean extends BaseActionBean {
    
    @ValidateNestedProperties({
        
        @Validate(field="username",required=true),
        @Validate(field="password",required=true,minlength=5),
        @Validate(field="email",required=true,mask="^([a-zA-Z0-9_\\.-]+)@([a-zA-Z0-9]+)([a-zA-Z0-9_\\.-]*)\\.([a-zA-Z]+)$")
    })
    private TUser newUser;
    
    @Validate(required=true,minlength=5)
    private String passwordRetype;
    
    @SpringBean("users")
    private UsersDao usersDao;
    
    private String errorMsg;
    
    // Actions
    @DefaultHandler
    public Resolution register() {
        
        if(getUsersDao().getUser(this.getNewUser().getUsername()) != null) {
            
            setErrorMsg("User already exists");
            return new ForwardResolution("/WEB-INF/jsp/error.jsp");
        }
        
        else {
            
            if(!this.getNewUser().getPassword().equals(getPasswordRetype())) {
                
                setErrorMsg("Passwords do not match.");
                return new ForwardResolution("/WEB-INF/jsp/error.jsp");
            }
            
            else {
                
                // Todo
                // Send email
                
                getUsersDao().addUser(newUser);
                getContext().setCurrentUser(newUser);
                getContext().getCurrentUser().calcRemainingTrips();
                return new ForwardResolution("/WEB-INF/jsp/trips.jsp"); // change back to home.jsp
            }
        }
    }

    // Accessors
    public TUser getNewUser() {
        return newUser;
    }

    public void setNewUser(TUser newUser) {
        this.newUser = newUser;
    }

    public String getPasswordRetype() {
        return passwordRetype;
    }

    public void setPasswordRetype(String passwordRetype) {
        this.passwordRetype = passwordRetype;
    }

    public UsersDao getUsersDao() {
        return usersDao;
    }

    public void setUsersDao(UsersDao usersDao) {
        this.usersDao = usersDao;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
